package com.wangsd.common.component;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.google.common.collect.Maps;
import com.wangsd.common.config.WxOpenProperties;
import com.wangsd.web.coupon.entity.Company;
import com.wangsd.web.coupon.service.CompanyService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class WxjavaService {

    @Autowired
    CompanyService companyService;
    @Autowired
    WxOpenProperties wxOpenProperties;

    private static Map<String, WxMaService> maServices = Maps.newHashMap();

    private static Map<String, WxMpService> mpServices = Maps.newHashMap();

    /**
     * 获取小程序服务类
     *
     * @param appid
     * @return
     */
    public WxMaService getMiniService(String appid) {
        WxMaService wxMaService = maServices.get(appid);
        if (wxMaService == null) {
            Company company = companyService.selectByMiniAppid(appid);
            wxMaService = new WxMaServiceImpl();
            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
            config.setAppid(appid);
            config.setSecret(company.getMiniSecret());
            config.setToken(company.getMiniToken());
            config.setAesKey(company.getMiniAesKey());
            wxMaService.setWxMaConfig(config);
            maServices.put(appid, wxMaService);
        }
        return wxMaService;
    }

    /**
     * 获取公众号服务类
     *
     * @param appid
     * @return
     */
    public WxMpService getMpService(String appid) {
        WxMpService wxMpService = mpServices.get(appid);
        if (wxMpService == null) {
            wxMpService = new WxMpServiceImpl();
            WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
            config.setAppId(appid);
            config.setSecret(wxOpenProperties.getWebSecret());
            wxMpService.setWxMpConfigStorage(config);
            mpServices.put(appid, wxMpService);
        }
        return wxMpService;
    }
}
